#include <cstdlib>
#include <iostream>
#include <cstring>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;

#define SIZE 1024

int main()
{
    //1. 创建管道
    int pipefd[2] = {0};
    if (pipe(pipefd) != 0) 
    {
        perror("pipe");
        exit(1);
    }
    
    // cout << "pipefd[0]:" << pipefd[0] << endl;
    // cout << "pipefd[1]:" << pipefd[1] << endl;

    //2. 创建子进程
    int pid = fork();
    if (pid == 0)
    {
        close(pipefd[0]); //3. 关闭文件描述符
        
        char msg[SIZE] = {0};
        int cnt = 0;
        while (true) 
        {
            snprintf(msg, sizeof(msg), "我是子进程[%d]，我要狠狠的写入%d", getpid(), cnt);
            write(pipefd[1], msg, strlen(msg));
            cnt++;
            sleep(1);
            //break;

            // char x = 'x';
            // write(pipefd[1], &x, 1);
            // cout << cnt << endl;
            // cnt++;
        }

        close(pipefd[1]);
        exit(0);
    }

    close(pipefd[1]); //3. 关闭文件描述符
                      
    //4. 通信
    while (true) 
    {
        char buff[SIZE] = {0};
        ssize_t s = read(pipefd[0], buff, sizeof(buff) - 1);

        sleep(1);
        break;

        if (s > 0)
        {
            buff[s] = '\0';
            cout << buff << endl;
            // sleep(2);
        }
        else if (s == 0)
        {
            std::cout << "read end-of-file" << std::endl;
            //break;
        }
        else
        {
            std::cout << "read error" << std::endl;
            break;
        }
    }

    close(pipefd[0]);

    int status = 0;
    int ret = waitpid(pid, &status, 0);
    if (ret > 0)
        cout << "exit code:" << (status >> 8) << "exit signal:" << (status & 0x7F) << endl;
    else
        perror("waitpid");

    

    return 0;
}
